import axios from 'axios'
import { ElMessage, ElLoading } from 'element-plus'
import { getMAC } from '@/utils/getMAC';
import { useUserStore } from '@/stores/user'

const instance = axios.create({
  baseURL: 'http://47.76.250.92:8808/api/uc',
  withCredentials: false,
})

// 请求拦截器
instance.interceptors.request.use(
  async config => {
    const macAddress = await getMAC();
    config = {
      neddLogin: true,
      ...config,
    }

    return config
  },
  error => {
    ElMessage.error('请求超时')
    Promise.reject(error)
  }
)

// 相应拦截器
instance.interceptors.response.use(
  response => {
    const { data, status } = response

    if (status && status == 200) {
      if ([401].includes(data.code)) {
        ElMessage.warning(data.msg || '账号已过期，请重新登录')
        const userStore = useUserStore()
        userStore.logout()
        return Promise.reject(data)
      } else if (data.code != 200) {
        ElMessage.error(data.msg)
        return Promise.reject(data)
      }

      return data.data
    } else {
      ElMessage.error('接口错误')
      return Promise.reject(data)
    }
  },
  error => {
    const status = error?.response?.status

    if (status == 500) {
      ElMessage.error('接口异常')
    } else if (status == 403 || status == 401) {
      ElMessage.warning(error?.response?.data?.msg || '账号已过期，请重新登录')
      const userStore = useUserStore()
      userStore.logout()
      return
    } else {
      ElMessage.error('请求失败，请稍后重试')
    }

    return Promise.reject(error)
  }
)

export const http = instance
export default instance
